import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const baseURL =
  process.env.NODE_ENV === 'production'
    ? 'https://api.yamero.cc'
    : 'http://8.138.96.41:9999'

// create an axios instance
const service = axios.create({
  baseURL, // Dynamically set baseURL
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你的用户登录凭证已经过期, 你可以选择重新留在此界面，或者登出', '确定登出', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * Method to download binary files (bypasses interceptors)
 * @param {string} url - The endpoint to download from
 * @param {object} params - Query parameters
 * @param {string} filename - Suggested filename for download
 * @returns {Promise<void>}
 */
export async function downloadBinary(url, filename = "downloaded_file") {
  try {
    const token = getToken(); // Manually retrieve token if needed
    const response = await axios.get(baseURL + url, {
      responseType: "blob", // Ensure binary data is properly handled
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    });

    // Create a blob URL
    const blob = new Blob([response.data], { type: response.headers["content-type"] });
    const downloadUrl = window.URL.createObjectURL(blob);

    // Create a link and trigger the download
    const link = document.createElement("a");
    link.href = downloadUrl;

    // Extract filename from headers, fallback to default
    const contentDisposition = response.headers["content-disposition"];
    if (contentDisposition) {
      const match = contentDisposition.match(/filename="?(.+?)"?$/);
      if (match) {
        filename = decodeURIComponent(match[1]); // Get filename from response headers
      }
    }

    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();

    // Clean up
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error("File download failed:", error);
    Message.error("文件下载失败!");
  }
}


export default service
